package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.entity.User;
import com.demo.mapper.UserMapper;
import com.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {
    @Override
    public boolean register(User user) {
        // 1. 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, user.getUserName());
        User existingUser = this.getOne(queryWrapper);

        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 2. 对密码进行MD5加密
//        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        log.info("encryptedPassword {}", user.getPassword());
        user.setPassword(user.getPassword());

        // 3. 保存用户信息
        return this.save(user);
    }
    @Override
    public User login(String username, String password) {
        // 1. 根据用户名查询用户
        log.info("String username, String password {} {}", username,password);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = this.getOne(queryWrapper);
        // 2. 用户不存在
        if (user == null) {
            log.info("用户不存在");
            return null;
        }
        log.info("user {}", user);
        // 3. 对用户输入的密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        log.info("encryptedPassword {}", encryptedPassword);
        // 4. 比较密码
        if (!encryptedPassword.equals(user.getPassword())) {
            log.error("密码错误");
            return null;
        }
        // 5. 返回用户信息
        return user;
    }
}
